#!/usr/bin/env bash
# SPDX-License-Identifier: BSD-3-Clause
# Copyright 2019, Intel Corporation

#
# src/test/rpmem_basic/TEST22 -- unit test for mixed workloads
# (rpmem_flush, rpmem_drain and rpmem_persist)
#

. ../unittest/unittest.sh

require_test_type medium

. setup.sh

setup

create_poolset $DIR/pool0.set 8M:$PART_DIR/pool0.part0 8M:$PART_DIR/pool0.part1
# Pool set file with the SINGLEHDR option
create_poolset $DIR/pool1.set 8M:$PART_DIR/pool1.part0 8M:$PART_DIR/pool1.part1 O SINGLEHDR
# Pool set file with the NOHDRS option
create_poolset $DIR/pool2.set 8M:$PART_DIR/pool2.part0 8M:$PART_DIR/pool2.part1 O NOHDRS

run_on_node 0 "rm -rf ${NODE_DIR[0]}$POOLS_DIR ${NODE_DIR[0]}$POOLS_PART && mkdir -p ${NODE_DIR[0]}$POOLS_DIR && mkdir -p ${NODE_DIR[0]}$POOLS_PART"

copy_files_to_node 0 ${NODE_DIR[0]}$POOLS_DIR $DIR/{pool0.set,pool1.set,pool2.set}

expect_normal_exit run_on_node 1 ./rpmem_basic$EXESUFFIX\
	test_create 0 pool0.set ${NODE_ADDR[0]} mem 8M none test_close 0

expect_normal_exit run_on_node 0 ./rpmem_basic$EXESUFFIX\
	fill_pool ${NODE_DIR[0]}$POOLS_DIR/pool0.set 1234

# limit size of WQ queue
export RPMEM_WORK_QUEUE_SIZE=8
export_vars_node 1 RPMEM_WORK_QUEUE_SIZE

# working buffers
POOL_SIZE=$(convert_to_bytes 8M)
FLUSH_OFF=${PAGE_SIZE} # POOL_HDR_SIZE
PERSIST_SIZE=${CACHELINE_SIZE}
FLUSH_OP_SIZE=${CACHELINE_SIZE}
PERSIST_OFF=$((POOL_SIZE - PERSIST_SIZE))

# scenarios
PERSIST_WQE=2 # WQ entries for single rpmem_persist
NFLUSHES[0]=$((RPMEM_WORK_QUEUE_SIZE - PERSIST_WQE)) # enough space for subsequent rpmem_persist
NFLUSHES[1]=$((RPMEM_WORK_QUEUE_SIZE - PERSIST_WQE + 1)) # only first WQ entry for rpmem_persist will fit
NFLUSHES[2]=$((RPMEM_WORK_QUEUE_SIZE)) # last WQ entry should trigger a WQ flush so WQ should be empty

# create command sequence
CMD=
SEED=
for persist_relaxed in 0 1; do
	for flush_relaxed in 0 1; do
		for i in ${!NFLUSHES[@]}; do
			SEED=$((4321 + i))
			nflushes=${NFLUSHES[$i]}
			FLUSH_SIZE=$((FLUSH_OP_SIZE * nflushes))

			CMD+="buff_limit 0 $FLUSH_OFF $FLUSH_SIZE "
			CMD+="test_flush 0 $SEED 1 $nflushes $flush_relaxed "
			CMD+="test_drain 0 1 "
			CMD+="buff_limit 0 $PERSIST_OFF $PERSIST_SIZE "
			CMD+="test_persist 0 $SEED 1 1 $persist_relaxed "
		done
	done
done

expect_normal_exit run_on_node 1 ./rpmem_basic$EXESUFFIX\
	test_open 0 pool0.set ${NODE_ADDR[0]} pool 8M init none\
	$CMD\
	test_close 0

expect_normal_exit run_on_node 0 ./rpmem_basic$EXESUFFIX\
	check_range ${NODE_DIR[0]}$POOLS_DIR/pool0.set $SEED $FLUSH_OFF $FLUSH_SIZE\
	check_range ${NODE_DIR[0]}$POOLS_DIR/pool0.set $SEED $PERSIST_OFF $PERSIST_SIZE

pass
